<template>
  <div class="category-wrapper">
    <div class="category-div">
      <type :tree-data="treeData" float @change="typeChange"></type>
      <template v-if="isShop">
        <div class="tag" @click="$router.push('/')">商城首页</div>
        <div class="tag" @click="$router.push('/demand/list')">需求大厅</div>
<!--        <div class="tag" @click="toJump">智能合规</div>-->

      </template>
    </div>
    <div class="current-wrapper" v-if="currentTypeList.length>0||currentTypeNames.length>0">
      <div>当前位置：</div>
      <template v-if="!operation">
        <template v-for="(item,index) in currentTypeNames">
          <div class="current-place">
            {{ item }}
          </div>
          <div class="current-split" v-if="index!==currentTypeNames.length-1">
            {{ '>' }}
          </div>
        </template>
        <div class="current-split" v-if="currentTypeNames.length>0">{{ '>' }}</div>
        <div class="current-place">
          商品详情
        </div>
      </template>
      <template v-else>
        <template v-for="(item,index) in currentTypeList">
          <div class="current-item" :id="'current_'+index">
            {{ item.name }}
            <svg-icon style="margin-left: 6px;" icon-class="down" size="12"></svg-icon>
          </div>
          <div class="current-split" v-if="index!==currentTypeList.length-1">
            {{ '>' }}
          </div>
        </template>
      </template>
      <div class="category-more" id="category-more">
        <div class="category-more-item"
             :class="{'active':item.id===currentTypeIds[activeCurrentIndex]}"
             v-for="(item,index) in displayData" @click="chooseItem(item,index)" :key="item.id">
          {{ item.name }}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Type from './Type'
import $ from 'jquery'
import {queryGoodsType} from '@/api/goods/type'

export default {
  name: 'ChooseType',
  components: { Type },
  props: {
    isShop:{
      type: Boolean,
      default: true
    },
    currentTypeNames: {
      type: Array,
      default: () => []
    },
    operation: {
      type: Boolean,
      default: true
    },
    defaultTypeId: ''
  },
  data () {
    return {
      list: [],
      preTree: [],
      treeData: [],
      currentTypeList: [],
      currentTypeIds: [],
      tempTypeList: [],
      activeCurrentIndex: 0,
      activeParentIndex: 0,
    }
  },
  computed: {
    displayData () {
      let treeone = this.preTree.filter(i => i.children && i.children.length > 0)
      let treetwo = this.preTree[this.activeParentIndex].children
      return this.activeCurrentIndex === 0 ? treeone : treetwo
      // return this.activeCurrentIndex === 0 ? this.treeData.filter(item => item.children && item.children.length > 0) : this.treeData[this.activeParentIndex].children
    }
  },
  watch: {
    defaultTypeId: {
      handler (newVal) {
        if (newVal && this.list.length > 0) {
          this.currentTypeIds = []
          this.currentTypeList = []
          this.findTree()
        }
      },
      immediate: true
    }
  },
  created () {
    this.loadTypeList()
  },
  methods: {
    toJump() {
      // const url = `https://www.baidu.com?userToken=${userToken}`
      const url = 'https://dthg.szdex.com:30921/home?userToken=${userToken}'

      // https://合规系统url?userToken=${userToken}
      window.open(url, '_self', 'noopener=yes,noreferrer=yes')

    },
    findTree(){
      const current = this.list.filter(item => item.id == this.defaultTypeId)[0]
      const parent = this.list.filter(item => item.id == current.parentId)[0]
      this.currentTypeList.push(parent, current)
      this.currentTypeIds.push(parent.id, current.id)
      this.activeParentIndex = this.preTree.findIndex(item => item.id === parent.id)
    },
    loadTypeList () {
      this.treeData = []
      this.preTree = []
      queryGoodsType().then(res => {
        if (res.code === 0) {
          // this.list = res.data
          this.treeData = this.generateTreeData(res.data)
          this.preTree = this.allTreeData(JSON.parse(JSON.stringify(res.data)))

          if (this.defaultTypeId) {
            this.findTree()
            this.$nextTick(() => {
              this.currentHoverEvent()
            })
          }
        }
      })
    },
    generateTreeData (list) {
      // 展示第二级分类
      let temp = list.filter(item => item.level === 2)
      for (let i = 0; i < temp.length; i++) {
        temp[i].children = list.filter(item => item.parentId === temp[i].id)
        temp[i].children.sort((a, b) =>a.sort - b.sort)
      }
      return temp
    },
    allTreeData(list){
      let temp = this.generateTreeData(list)
      // 生成带有全部的 树状数据
      temp.map(v=>{
        let id = v.id == 'all' ? 'all' : ('all' + v.id)
        let all = { name: '全部', id, parentId: v.id, level: 3, pid: v.id }
        if(v.children.length > 0)v.children.unshift(all)
      })
      // 解构不影响原数组
      let children = list.reduce((p,v)=>{
        if(v.level === 3){
          let { id, parentId, name, fullName, level } = v
          parentId = 'all'
          id = 'all' + id
          p.push({ id, parentId, name, level, pid: v.id })
        }
        return p
      },[])
      children.unshift({name:'全部',id: 'allall', level: 3,parentId: "all", pid: '' })
      temp.unshift({ name: '全部', id: 'all', level: 2, parentId: "1599723733286621185", pid: '', children })
      // 二维数组
      this.list = temp.reduce((p,v)=>{
        let obj = JSON.parse(JSON.stringify(v))
        let children = obj.children
        delete obj.children
        children.unshift(obj)
        return p.concat(...children)
      },[])
      return temp
    },
    currentHoverEvent () {
      const that = this
      $('.current-item').mouseenter(function (e) {
        const $this = $(this)
        $this.addClass('active')
        $this.siblings().removeClass('active')
        const index = $this.attr('id').split('_')[1]
        that.activeCurrentIndex = Number(index)
        if (!$('#category-more').hasClass('show')) {
          $('#category-more').addClass('show')
        }
      }).mouseleave(function () {
        $(this).removeClass('active')
        $(this).siblings().removeClass('active')
        if ($('#category-more').hasClass('show')) {
          $('#category-more').removeClass('show')
        }
      })
      $('#category-more').mouseenter(function () {
        $(this).addClass('show')
        if (!$('.current-item').eq(that.activeCurrentIndex).hasClass('active')) {
          $('.current-item').eq(that.activeCurrentIndex).addClass('active')
        }
        if (!$('#category-more').hasClass('show')) {
          $('#category-more').addClass('show')
        }
      }).mouseleave(function () {
        $(this).removeClass('show')
        if ($('.current-item').eq(that.activeCurrentIndex).hasClass('active')) {
          $('.current-item').eq(that.activeCurrentIndex).removeClass('active')
        }
        if ($('#category-more').hasClass('show')) {
          $('#category-more').removeClass('show')
        }
      })
    },
    chooseItem (item, index) {
      this.$set(this.tempTypeList, this.activeCurrentIndex, item)
      if (item.level < 3) {
        this.activeParentIndex = index
        this.activeCurrentIndex += 1
        $('.current-item').eq(this.activeCurrentIndex).addClass('active')
      } else {
        $('.current-item').eq(this.activeCurrentIndex).removeClass('active').siblings().removeClass('active')
        $('#category-more').removeClass('show')
        this.currentTypeIds = this.tempTypeList
        this.currentTypeList = this.tempTypeList
        this.currentTypeIds.splice(0, 0)
        this.currentTypeList.splice(0, 0)
        this.activeCurrentIndex = 0
        this.activeParentIndex = 0
        this.tempTypeList = []
        this.tempTypeList.splice(0, 0)
        let param = this.currentTypeIds[this.currentTypeIds.length - 1]
        // param = param.id || ''
        let id = param.id == ('all' + param.parentId) ? param.parentId: param.id
        id = id == 'all' ? '' : id
        this.$emit('change', this.currentTypeIds[this.currentTypeIds.length - 1])
      }
    },
    typeChange (e) {
      this.tempTypeList = []
      this.tempTypeList.splice(0, 0)
      this.activeCurrentIndex = 0
      this.activeParentIndex = 0
      this.$emit('change', e)
    }
  }
}
</script>

<style scoped lang="scss">
$width: 1200px;
$mainColor: #0078FE;
.tag{
  font-size: 16px;
  font-weight: 700;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0 25px;
  cursor: pointer;
}
.category-wrapper {
  background: #FAFAFA;
  width: 100%;
  height: 46px;
  margin-bottom: 60px;
  .category-div {
    width: $width;
    height: 100%;
    margin: auto;
    display: flex;
    position: relative;
  }

  .category-more {
    position: absolute;
    left: 59px;
    top: 26px;
    width: 830px;
    height: 70px;
    background: white;
    z-index: 999;
    display: none;
    padding-right: 10px;
    padding-bottom: 10px;
    border-radius: 0 4px 4px 4px;
    border: 1px solid $mainColor;
    flex-wrap: wrap;

    &.show {
      display: flex;
    }

    .category-more-item {
      margin-left: 10px;
      margin-top: 10px;
      font-size: 12px;
      cursor: pointer;
      font-family: PingFangSC-Regular, PingFang SC, sans-serif;
      font-weight: 400;
      color: #323232;
      line-height: 12px;

      &:hover {
        color: $mainColor;
      }

      &.active {
        color: $mainColor;
      }
    }
  }
}

.current-wrapper {
  width: $width;
  margin: auto;
  position: relative;
  display: flex;
  align-items: center;
  // padding: 0 30px;
  margin-top: 10px;
  font-size: 12px;
  font-family: PingFangSC-Regular, PingFang SC, sans-serif;
  font-weight: 400;
  color: #C7C7C7;
  line-height: 12px;

  .current-item {
    background: #FFFFFF;
    border-radius: 2px;
    border: 1px solid #E2E2E2;
    color: #323232;
    padding: 6px 10px;
    cursor: pointer;

    svg {
      rotate: 0deg;
      transition: rotate .3s;
    }

    &.active {
      border-color: $mainColor;
      border-bottom: none;
      border-bottom-right-radius: 0;
      border-bottom-left-radius: 0;
      color: $mainColor;

      svg {
        rotate: 180deg;
        transition: rotate .3s;
      }
    }
  }

  div:first-child {
    color: #646464;
  }

  .current-place {
    color: #323232;
  }

  .current-split {
    margin: 0 10px;
  }
}
</style>
